/*******************************************************************************
 * 版权：北京润尼尔网络科技有限公司，保留所有版权<br>
 * 版本：v1.0.0<br>
 * 文件：SimResult.js<br>
 * 日期：2017年8月9日<br>
 * 作者: 王中山<br>
 * 功能：应用程序上下文<br>
 * 
 * 修改记录：<br>
 * 日期 描述 更新功能<br>
 * 
 ******************************************************************************/
Rainier.UI.V2.SimResult = Rainier.Basic.CompositeObject.extend({
    
    NAME : "Rainier.UI.V2.SimResult",
    
    init : function(){

        this._super();

        this.matData     = null; //.mat数据文件内容
        this.consoleData = null; //octave控制台信息
        this.figureList  = new draw2d.util.ArrayList(); //图元文件内容
        this.wsResultBuffer = ''; //WS数据缓存
        
        this.wsPackageCount  = 0; //WS发送的数据包个数
        this.wsPackageSize   = 0; //WS发送的数据包大小
        this.wsFileNameList  = new draw2d.util.ArrayList(); //WS发送的文件名称列表
        
    },

    clear : function(){
                
        this.matData = null;
        this.consoleData = null;
        this.wsResultBuffer = '';
        this.figureList.clear();
        
        this.wsPackageCount  = 0;
        this.wsPackageSize   = 0;
        this.wsFileCount     = 0;
        this.wsFileNameList.clear();
    },

    parseHeadInfo : function(strInfoData){
        //"@@OutputStart@@DataCount:244@DataSize:1024@FileCount:4@FileList:[out.txt#exp1-figure1.svg#exp1-figure2.svg#exp1-data.mat]"
        strInfoData = strInfoData.replace("@@OutputStart@@","");
        var _this     = this;
        var infoArray = strInfoData.split("@");
        $.each(infoArray,function(i,ele){
           var eleArray = ele.split(":");
           if(eleArray[0].match("DataCount")){
               var number1 = Number(eleArray[1]);
               _this.wsPackageCount = number1;
           }
           if(eleArray[0].match("DataSize")){
               var number2 = Number(eleArray[1]);
               _this.wsPackageSize = number2;
           }
           if(eleArray[0].match("FileCount")){
               var number3 = Number(eleArray[1]);
               _this.wsFileCount = number3;
           }
           if(eleArray[0].match("FileList")){
               var strEle = eleArray[1]; 
               strEle = strEle.replace("FileList:","");
               strEle = strEle.replace("[","");
               strEle = strEle.replace("]","");
               var fileNames = strEle.split("#");
               $.each(fileNames,function(i,f){
                   _this.wsFileNameList.add(f);
               });
           }
        });
    },

    appendWsData : function(strEventData){
        //DATA[244/243/892]@[zYgMC44ODg1Mz.....wNzYgMC45OTY4MTUyODY2MjQyMDM4IDEKCgoA]]
        var dataArray = strEventData.split("@");
        var dataHead  = dataArray[0];
        var data      = dataArray[1];
        var total     = 0;
        var number    = 0;
        var size      = 0;
        dataHead = dataHead.replace("DATA[","");
        dataHead = dataHead.replace("]","");
        var dataHeadArray = dataHead.split("/");
        total = Number(dataHeadArray[0]);
        number= Number(dataHeadArray[1]);
        size  = Number(dataHeadArray[2]);
        
        var _data = data.substring(1,data.length-1);
        this.wsResultBuffer += _data;

        //app.resultViewPage.resultPanel.setOption("content","<h1>解算进度: "+parseInt((number+1)*100/total)+"%</h1>");
        if((number+1) === total){
            this.parseDataInfo();
        }
    },


    parseDataInfo : function(){
        var _this     = this;
        var dataArray = this.wsResultBuffer.split("*****");
        var dataInfo  = null;
        $.each(dataArray,function(i,fileData){
            var fileDataArray = fileData.split("###");
            var fileName      = fileDataArray[0].substring(1,fileDataArray[0].length-1);
            var fileData      = fileDataArray[1].substring(1,fileDataArray[1].length-1);
            
            //base64解码文件内容
            try{
                var fileData_ = $.base64.decode(fileData);
                if (fileData_) {                
                    if(fileName === "out.txt"){
                        _this.consoleData = fileData_;
                    }
                    if(fileName.endsWith(".svg")){
                        var dataObj = {fileName:fileName,content:fileData_};
                        _this.figureList.add(dataObj);
                        var storage = window.localStorage;
                        storage.setItem(fileName,fileData_);
                    }
                    if(fileName.endsWith(".mat")){
                        _this.matData = fileData_;
                        dataInfo = _this.parseMat(fileData_);  
                        console.log(dataInfo);
                        //序列化的过程；                                                                    
                        // var computeResult = dataInfo.serialize(); 
                        // //数据的本地存储,保存的时候获取
                        // var storage = window.localStorage;
                        // storage.setItem("dataInfo",JSON.stringify(computeResult));
                    }
                }
            }
            catch(e){
                console.log(e);
            }
            //app.resultViewPage.resultPanel.setOption("content","<h1>解码进度: "+parseInt((i+1)*100/dataArray.length)+"%</h1>");
        });
        this.doPlot(dataInfo);
        this.restoreDefaultPlatform();
        this.clear();
    },


    doPlot : function(dataInfo){

        var expermentalResult      = window.app.getResultComponent();
        expermentalResult.clickToShow();
        var uiFigure        = expermentalResult.resultPanel;//图形显示面板
        var variableData    = expermentalResult.variableTable;
        var uiConsole       = expermentalResult.consoleTextBox;
        // var expctx = app.resultViewPage;
        // var exp3D  = app.babylonViewPage;
        // var uiConsole    = expctx.consoleTextBox;
        // var uiData       = expctx.variablePanel;
        // var uiFigure     = expctx.resultPanel;
        // var variableData = expctx.variableTable;
        // var ui3D         = exp3D.currentExper;
        
        
        var str="";
        if (this.figureList.getSize() < 1) {
            str += ("<div>无图片显示</div>");
        }
        this.figureList.each(function(i,fd){
            str += ("<div class='svgPlot'>" + fd.content + "</div>");
        });
        
        if(uiFigure){
            uiFigure.setOption("content",str);
        }

        if(variableData){
            variableData.createTableViewPage(dataInfo);
        }

        uiConsole.setText(this.consoleData);

    },
    clearPlot : function(){
        var expermentalResult= window.app.getResultComponent();
        var uiFigure         = expermentalResult.resultPanel;//图形显示面板
        var variableData     = expermentalResult.variableTable;
        var uiConsole        = expermentalResult.consoleTextBox;
        // var expctx = app.resultViewPage;
        // var uiConsole = expctx.consoleTextBox;
        // var uiData    = expctx.variablePanel;
        // var uiFigure  = expctx.resultPanel;

        // uiConsole.setOption('content',"<h1></h1>");
        // //uiData.setOption('content',"<h1></h1>");
        if(uiFigure){
            uiFigure.setOption("content","");
        }
        if(variableData){
            variableData.variableTable.clear();
        }
        uiConsole.setText('');
    },

    parseMat : function(mat){
        var headIndex   = mat.indexOf('\n');
        var body        = mat.slice(headIndex + 1).replace(/ |#/g,' ');
        var dataArray   = body.split(/\n\s*\n|\r\n\s*\r\n/);
        var matObjList  = new  draw2d.util.ArrayList();
        $.each(dataArray,function(i,data){
            var arg     = {};
            var index = data.lastIndexOf(":");
            var weili = data.substring(index+1,data.length);
            var weiliIndex = weili.indexOf("\n");
            var weiliText = weili.slice(weiliIndex+1);
            
            var objArr  = data.split('\n');
            arg.valueList= new draw2d.util.ArrayList();
            $.each(objArr,function(j,obj){
                if (obj.indexOf(':') >= 0) {
                  var obj = obj.replace(/\s*/g,"");//去掉空格
                  var a = obj.split(':');
                  arg[a[0]] = a[1];
                }
                else{
                  var obj = obj.replace(/^\s*/g,"");
                  arg.valueListText = weiliText;
                  if(obj.indexOf(" ") != -1){
                     var valueObjArr = obj.split(" ");
                     for(var i=0;i<valueObjArr.length;i++){
                        (/[A-Za-z]/.test(valueObjArr[i])) ? "return true" : arg.valueList.add(valueObjArr[i]);                              
                     }
                  }else{
                    arg.valueList.add(obj);
                  }
                }
            })
            var argName = arg.name;
            var argType = arg.type;
            if(argName || argType){
                var argName=argName.replace(/[\r\n]/g,"");
                var argType=argType.replace(/[\r\n]/g,"");
            }
            if (argName === '<cell-element>' || argType === 'cell' || argType === 'class') {
                return true;
            }
            else{
                if(argName){
                    matObjList.add(arg);
                }
            }

        })
        console.log(matObjList);
        return matObjList;
    },

    restoreDefaultPlatform : function(){
        var runDom = $(".app-run");
        var shade  = $(".app-running-shade");
        if(runDom){
           runDom.removeClass("app-control-btn-run-on").addClass("app-control-btn-run");
        }
        if(shade){
            shade.remove();
        }

    }
});